package com.shop.mms_client.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.Telephony;
import android.telephony.SmsMessage;
import com.shop.mms_client.api.ApiManager;
import com.shop.mms_client.model.DetectionResult;
import com.shop.mms_client.model.Message;
import com.shop.mms_client.repository.MessageRepository;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import com.shop.mms_client.utils.ErrorHandler;

public class SmsReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) {
            SmsMessage[] messages = Telephony.Sms.Intents.getMessagesFromIntent(intent);
            
            for (SmsMessage sms : messages) {
                String sender = sms.getDisplayOriginatingAddress();
                String content = sms.getMessageBody();
                
                // 调用API检测垃圾短信
                ApiManager.getInstance().detectText(content, sender)
                    .enqueue(new Callback<DetectionResult>() {
                        @Override
                        public void onResponse(Call<DetectionResult> call, Response<DetectionResult> response) {
                            if (response.isSuccessful() && response.body() != null) {
                                DetectionResult result = response.body();
                                // 保存消息到数据库
                                Message message = new Message(sender, content, null, result.isSpam());
                                MessageRepository.getInstance(context).insertMessage(message);
                                
                                // 如果是垃圾短信，阻止广播继续传递
                                if (result.isSpam()) {
                                    abortBroadcast();
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<DetectionResult> call, Throwable t) {
                            // 保存消息但标记为非垃圾信息
                            Message message = new Message(sender, content, null, false);
                            MessageRepository.getInstance(context).insertMessage(message);
                            
                            // 处理错误
                            ErrorHandler.handleApiError(context, t);
                        }
                    });
            }
        }
    }
} 